<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { CheckboxValueType } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  options: {
    type: Array,
    default: () => [],
  },
  labelName: {
    type: String,
    default: 'All',
  },
})

const emits = defineEmits(['update:modelValue', 'change'])

const innerValue = computed({
  get: () => props.modelValue,
  set: (newValue) => {
    emits('update:modelValue', newValue)
  },
})

const checkAll = ref(false)
const indeterminate = ref(false)

watch(innerValue, (val) => {
  if (val.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (val.length === props.options.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
})

const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false
  if (val) {
    innerValue.value = props.options.map((_) => _.value)
  } else {
    innerValue.value = []
  }
}

const handleCheckedChange = (value: CheckboxValueType[]) => {
  emits('change', value)
}
</script>

<template>
  <div class="checkbox">
    <div class="check-all">
      <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
        {{ labelName }}
      </el-checkbox>
    </div>
    <div style="padding-left: 24px">
      <el-checkbox-group v-model="innerValue" @change="handleCheckedChange">
        <el-space direction="vertical">
          <el-checkbox v-for="item in options" :key="item.id" :label="item.id">
            {{ item.value }}
          </el-checkbox>
        </el-space>
      </el-checkbox-group>
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
